package com.littlerpc.registry.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

/**
 * Created by ChengPeng on 2017/7/5.
 */
public final class ZookeeperUtils {

    private static byte [] EMPTY_BYTE = new byte[0];
    private static String EMPTY_STR = "";

    /**
     *
     * @param zk
     * @param parentNodePath
     * @param nodePath
     * @return
     */
    protected static String getData(ZooKeeper zk,String parentNodePath,String nodePath) {
        try {
            byte[] data = zk.getData(parentNodePath + "/" + nodePath, false, null);
            return new String(data);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return EMPTY_STR;
    }

    /**
     * 创建节点
     * @param zk
     * @param nodePath
     * @param nodeData
     * @param createMode
     */
    protected static void createNode(ZooKeeper zk,String nodePath,String nodeData,CreateMode createMode) {
        try {
            //判断节点是否已经创建
            Stat exists = zk.exists(nodePath, false);
            if (exists == null) {
                zk.create(nodePath, nodeData != null ? nodeData.getBytes() : EMPTY_BYTE, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
            }
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
